<?php

namespace App\Repository\Anchor;

use App\Models\Anchor\AnchorAuthorModel;
use App\Models\Anchor\AnchorWorksModel;
use App\Models\LogsModel;
use App\Models\Orders\OrdersUserModel;
use App\Repository\BaseRepository;

class AnchorWorksRepository extends BaseRepository
{
    public $model;

    public function __construct()
    {
        $this->model = new AnchorWorksModel();
        parent::__construct();
    }

    public function index($params, $page = 1, $limit = 10)
    {
        $where = [];
        //        主播要特殊处理
        if (isset($params['anchor_id']) && !empty($params['anchor_id'])) {
            $where['eq']['anchor_id'] = $params['anchor_id'];
        }
        //        达人条件
        if (isset($params['author_id']) && !empty($params['author_id'])) {
            $where['eq']['author_id'] = $params['author_id'];
        }
        if (!empty($params['dateRange'])) {
            $time = $params['dateRange'];
            $where['between'] = ['created_at' => [$time]];
        }
        if (isset($params['status']) && $params['status'] != '') {
            $where['eq']['status'] = $params['status'];
        }
//        先要总数
        $totalRows = $this->model->searchWhere($where)->count('id');
//        再加上分页查询
        $rows = $this->model->page($page, $limit)->with(["type" => function ($query) {
            $query->select(['id', 'name']);
        }, "anchor" => function ($query) {
            $query->select(['id', 'nickname']);
        }, "author" => function ($query) {
            $query->select(['id', 'author_id', 'nickname']);
        }])->select(['*'])->searchWhere($where)->orderByDesc('id')->get();

        if (!empty($rows)) {
            $Repository = new AnchorStatsRepository();
            $Repository->countWorksOrdersData($rows);
        }
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

//实时查找订单数据
//    public function countRealOrdersSale(&$rows)
//    {
//        $startTime = '';
//        $overTime = '';
//        $authorId = [];
//        foreach ($rows as $k => $v) {
////            找最小的开始时间
//            if (empty($startTime)) {
//                $startTime = $v['created_at'];
//            } else {
//                if (strtotime($v['created_at']) < strtotime($startTime)) {
//                    $startTime = $v['created_at'];
//                }
//            }
////            找最大的结束时间
//            if (empty($v['over_at'])) {
//                $v['over_at'] = date('Y-m-d H:i:s');
//            }
//            if (empty($overTime)) {
//                $overTime = $v['over_at'];
//            } else {
//                if (strtotime($v['over_at']) > strtotime($overTime)) {
//                    $overTime = $v['over_at'];
//                }
//            }
////            统计内容初始化
////            时长
//            $rows[$k]['second'] = strtotime($v['over_at']) - strtotime($v['created_at']);
//            $rows[$k]['sales'] = 0;
//            $rows[$k]['commission'] = 0;
//            $authorId[] = $v['author_id'];
//        }
//        $where = [];
//        $where['in']['author_id'] = array_unique($authorId);
//        $where['between']['created_at'] = [$startTime, $overTime];
//        $ModelOrdersUser = new OrdersUserModel();
////        $orders = [];
//        foreach ($ModelOrdersUser->select(['author_id', 'author_commission', 'created_at'])->searchWhere($where)->cursor() as $row) {
//            $ordersTime = strtotime($row['created_at']);
//            foreach ($rows as $k => $v) {
//                $workStartTime = strtotime($v['created_at']);
//                $workOverTime = empty($v['over_at']) ? time() : strtotime($v['over_at']);
//                if ($v['author_id'] == $row['author_id'] && ($ordersTime >= $workStartTime && $ordersTime <= $workOverTime)) {
//                    if (isset($rows[$k]['sales'])) {
//                        $rows[$k]['sales'] += 1;
//                    } else {
//                        $rows[$k]['sales'] = 1;
//                    }
////                                        计算佣金
//                    if (isset($rows[$k]['commission'])) {
//                        $rows[$k]['commission'] += $row['author_commission'];
//                    } else {
//                        $rows[$k]['commission'] = $row['author_commission'];
//                    }
//                }
//            }
//        }
//    }

    public function logs($where, $page = 1, $limit = 10)
    {
        $pk = $this->model->getKeyName();
//        先要总数
        $totalRows = $this->model->count($pk);
//        再加上分页查询
        $rows = $this->model->page($page, $limit)->with(["type" => function ($query) {
            $query->select(['id', 'name']);
        }, "anchor" => function ($query) {
            $query->select(['id', 'nickname']);
        }, "author" => function ($query) {
            $query->select(['id', 'author_id', 'nickname']);
        }])->select(['*'])->selectRaw('TIMESTAMPDIFF(SECOND,created_at, IFNULL(over_at,now())) AS second')->searchWhere($where)->get();
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

//新增
    public function add($request)
    {
//        达人id
        $authorId = $request->get('author_id');
        $hasOpen = $this->model->where(['author_id' => $authorId, 'status' => 0])->count('id');
        if ($hasOpen > 0) {
            return $this->returnMsg(1, '此达人已经在开播,不能新开');
        }
        //        如果提交过来有结束时间，那么这个是补录的，要查出单数据
        $willCheckOrders = false;
        $whereOrders = [];
        if ($request->has('over_at') && !empty($request->get('over_at'))) {
            $whereOrders[] = ['created_at', '<=', $request->get('over_at')];
            $willCheckOrders = true;
        }
        if ($request->has('created_at') && !empty($request->get('created_at'))) {
            $startTime = strtotime($request->get('created_at'));
//            开播后5分钟才记录，要查一下有没有出单记录
            if (time() - $startTime > 300) {
                $whereOrders[] = ['created_at', '>=', $request->get('created_at')];
                $willCheckOrders = true;
            }
        }
        $sales = 0;
        $ModelAuthor = new AnchorAuthorModel();
        $anchorId = $request->get('anchor_id');
//        $row = $ModelAuthor->where(["author_id" => $authorId, "anchor_id" => $anchorId])->select(["anchor_id"])->first();
//        if (empty($row)) {
//            return $this->returnMsg(1, '主播或达人不存在');
//        }
//        $request->offsetSet('author_id', $row['author_id']);
//        if ($willCheckOrders) {
//            $whereOrders[] = ['author_id', '=', $authorId];
//            $ModelOrdersUser = new OrdersUserModel();
////            $sales = $ModelOrdersUser->where($whereOrders)->count('id');
//        }
        $request->offsetSet('sales', $sales);
        return $this->unifiedAdd($request);
    }

//    修改直播时间段
    public function editTimes($request)
    {
        $id = intval($request->get('id'));
        $whereOrders = [];
        $update = [];
        if ($request->has('over_at') && !empty($request->get('over_at'))) {
            $whereOrders[] = ['created_at', '<=', $request->get('over_at')];
            $update['over_at'] = $request->get('over_at');
        }
        if ($request->has('created_at') && !empty($request->get('created_at'))) {
            $whereOrders[] = ['created_at', '>=', $request->get('created_at')];
            $update['created_at'] = $request->get('created_at');
        }
        $row = $this->model->where(["id" => $id])->select(["author_id"])->first();
        if (empty($row)) {
            return $this->returnMsg(1, '主播数据不存在');
        }
        $whereOrders[] = ['author_id', '=', $row['author_id']];
        $ModelOrdersUser = new OrdersUserModel();
//        $sales = $ModelOrdersUser->where($whereOrders)->count('id');
//        更新数据
//        $update['sales'] = $sales;
        if (false !== $this->model->where(["id" => $id])->update($update)) {
//            记录操作日志
            $ModelLogs = new LogsModel();
            $logContent = '修改了直播时间段';
            $ModelLogs->saveIt(1, $request->user->id, $id, $logContent);
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(2, '修改异常');
    }

//换播
    public function exchange($request)
    {
        $id = (int)$request->get('id');
        $authorId = (int)$request->get('author_id');
        $oldData = $this->model->where(['id' => $id])->first();
        if ($oldData['author_id'] == $authorId) {
            return $this->returnMsg(1, '还是那个达人啊');
        }
//        达人是不是这个主播的
        $ModelAuthor = new AnchorAuthorModel();
        if ($ModelAuthor->where(['author_id' => $authorId, 'anchor_id' => $oldData['anchor_id']])->count('id') <= 0) {
            return $this->returnMsg(1, '达人不是这个主播下面的人员啊');
        }
//        原达人下线，新达人上线

//            新增
        $data = $request->only(['anchor_id', 'author_id', 'anchor_type_id']);
//        print_r($data);

        $res = $this->model->insert($data);
        if ($res) {
            $this->offLine($id);
            return $this->returnMsg(200, '换播操作成功');
        }

        return $this->returnMsg(2, '换播操作不成功');
    }

//设置推广金额
    public function setCost($params)
    {
        $where = [];
        if (is_array($params['id'])) {
            if (count($params['id']) > 1) {
                $where['in']['id'] = $params['id'];
            } else {
                $where['eq']['id'] = $params['id'][0];
            }
        } else {
            $where['eq']['id'] = $params['id'];
        }
        $updata = [
            'cost' => floatval($params['money'])
        ];
        if (false !== $this->model->searchWhere($where)->update($updata)) {
            return $this->returnMsg(200, '操作完成');
        }
        return $this->returnMsg(2, '设置异常');
    }

//    下播操作
    public function offLine($id)
    {
//        把数据统计到times表
        $data = $this->model->where(['id' => $id])->first();
        //        把状态关了
        $updata = [
            'over_at' => date('Y-m-d H:i:s'),
            'status' => 1
        ];
        if (false !== $this->model->where(['id' => $id])->update($updata)) {
            return true;
        }
        return false;
    }

    public function del($id, $shopId = 0)
    {
//        可以多选的情况
        $ids = explode(',', $id);
        $where = [];
        if ($shopId != SUPPER_SHOP_ID) {
            $where['shop_id'] = $shopId;
        }
        if (count($ids) === 1) {
            $where['eq']['id'] = $ids[0];
        } else {
            $where['in']['id'] = $ids;
        }
        $this->model->searchWhere($where)->delete();
        return $this->returnMsg(200, '删除操作完成');
    }

}
